import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { System } from "./system.entity";
import { In, Repository } from "typeorm";
import { Http } from "src/util/http";
import { UserService } from "src/user/user.service";
import { DeptRoleEnum, RoleEnum } from "src/role/role.enum";
import { DeptService } from "src/dept/dept.service";



@Injectable()
export class SystemService {
    constructor(
        @InjectRepository(System)
        public readonly system: Repository<System>,
        private readonly userService: UserService,
        private readonly deptService: DeptService
    ) { }

    async create(data: System) {
        if (!!await this.system.findOne({
            where: {
                name: data.name
            }
        })) throw Http.forbidden("职场已存在")
        const entity = await this.system.save(this.system.create({
            name: data.name
        }))
        await this.deptService.create("人事部", entity, false, DeptRoleEnum.personnel);
        await this.deptService.create("商务部", entity, false, DeptRoleEnum.business);
        await this.deptService.create("财务部", entity, false, DeptRoleEnum.finance);
        await this.deptService.create("行政部", entity, false, DeptRoleEnum.administration);
        const proj = await this.deptService.create("项目部", entity, false);
        await this.deptService.create("1部", entity, true, DeptRoleEnum.member, proj);
        return entity
    }

    async setAdmin(ids: number[]) {
        const users = (await this.userService.findsBy({
            id: In(ids)
        })).filter(e => e.role !== RoleEnum.boos);
        return this.userService.userSys.save(users.map(e => {
            e.role = RoleEnum.director
            return e;
        }))
    }
}